package com.auto.qinglong.ui.screens

import android.util.Log
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Article
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.DoDisturbOn
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import com.auto.base.ui.HandleUiEvent
import com.auto.qinglong.net.FabAction
import com.auto.qinglong.net.client.beans.Task
import com.auto.qinglong.net.client.beans.TaskGroupTagBean
import com.auto.qinglong.net.client.beans.TaskStateCode
import com.auto.qinglong.ui.viewmodel.HomeViewModel
import kotlin.math.roundToInt

/**
 * Created by YuanWei1 on 2025/6/12.
 *
 * Description:
 */
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
@Composable
fun HomeScreen(
    viewModel: HomeViewModel, navController: NavHostController, checkLog: (Task) -> Unit = {}
) {
    HandleUiEvent(viewModel, navController)
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    var expanded by remember { mutableStateOf(false) }
    val pagingItems = viewModel.pageFlow.collectAsLazyPagingItems()
    // 1. 是否正在刷新
    val isRefreshing = pagingItems.loadState.refresh is LoadState.Loading

    Scaffold(topBar = {
        TitleBar()
    }, floatingActionButton = {
//        ExpandableFab(
//            actions = listOf(FabAction("环境变量") {
//                /* runTask() */
//                expanded = false
//            }, FabAction("订阅管理") {
//                /* checkLog() */
//                expanded = false
//            }),
//            icon = if (expanded) Icons.Default.Close else Icons.Default.Add,
//            expanded = expanded,
//            onFabClick = { expanded = !expanded })
    }) {
        Column(
            Modifier.padding(it)
        ) {
            SingleSelectChipGroup(uiState.groupTags, uiState.selectTags) {
                viewModel.saveSelectTaskGroupTagBean(it)
//                pagingItems.refresh()
            }
            PullToRefreshBox(isRefreshing, onRefresh = {
                pagingItems.refresh()
            }) {
                LazyColumn() {
                    items(pagingItems.itemCount) { index ->
                        val task = pagingItems[index]
                        if (task != null) {
                            SwipeToRevealItem(
                                id = task.key,
                                expandedId = uiState.expandedTaskId,
                                onExpandChange = { viewModel.updateExpandedTaskId(task.key) },
                                revealContent = {
                                    IconButton(
                                        modifier = Modifier.padding(horizontal = 16.dp), onClick = {
                                            viewModel.deleteTask(task)
                                        }) {
                                        Icon(Icons.Default.Delete, contentDescription = "删除")
                                    }
                                }) {
                                TaskItem(task, runTask = {
                                    viewModel.runTask(it)
                                }, checkLog = {
                                    checkLog(it)
                                })
                            }
                        }
                    }
                }
            }
        }
    }

    // 删除后刷新 + 恢复滚动位置
    LaunchedEffect(Unit) {
        viewModel.refreshListEvent.collect {
            pagingItems.refresh()
        }
    }
}

@Composable
fun TaskItem(item: Task, runTask: (Task) -> Unit = {}, checkLog: (Task) -> Unit = {}) {
    var isExpanded by remember { mutableStateOf(false) }
    Column(
        modifier = Modifier
            .background(Color.White)
            .clickable {
                isExpanded = !isExpanded
            }
            .fillMaxWidth()) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(item.name, style = MaterialTheme.typography.titleMedium)
                Text(item.command, style = MaterialTheme.typography.bodySmall)
            }
            IconButton(onClick = {
                runTask(item)
            }) {
                when (item.stateCode) {
                    TaskStateCode.STATE_RUNNING -> {
                        Icon(Icons.Default.Pause, contentDescription = "运行中")
                    }

                    TaskStateCode.STATE_LIMIT -> {
                        Icon(Icons.Default.DoDisturbOn, contentDescription = "禁止")
                    }

                    TaskStateCode.STATE_WAITING -> {
                        Icon(Icons.Default.Schedule, contentDescription = "列队中")
                    }

                    else -> {
                        Icon(Icons.Default.PlayArrow, contentDescription = "执行")
                    }
                }
            }
            IconButton(onClick = {
                checkLog(item)

            }) {
                Icon(Icons.Default.Article, contentDescription = "日志")
            }
        }
        // 可展开部分
        AnimatedVisibility(visible = isExpanded) {
            Column(modifier = Modifier.padding(horizontal = 16.dp)) {
                TaskEntry("状态", item.state)
                TaskEntry("定时", item.schedule)
                TaskEntry("上次运行时间", item.lastExecuteTime)
                TaskEntry("上次运行时常", item.lastRunningTime)
                TaskEntry("下次运行时间", item.nextExecuteTime)
            }
        }
        HorizontalDivider()
    }
}

@Composable
fun SwipeToRevealItem(
    id: String,
    expandedId: String?,
    onExpandChange: (String?) -> Unit,
    revealContent: @Composable () -> Unit,
    content: @Composable () -> Unit
) {
    var revealWidth by remember { mutableIntStateOf(0) }
    var offsetX by remember { mutableFloatStateOf(0f) }

    val maxOffset = -revealWidth.toFloat()
    val animatedOffset by animateFloatAsState(targetValue = offsetX, label = "SwipeOffset")

    // 若不是当前展开项，应收起
    LaunchedEffect(expandedId) {
        if (expandedId != id && offsetX != 0f) {
            offsetX = 0f
        }
    }

    Box(
        modifier = Modifier.pointerInput(revealWidth) {
            detectHorizontalDragGestures(onDragEnd = {
                if (offsetX < maxOffset / 2) {
                    offsetX = maxOffset
                    onExpandChange(id)
                } else {
                    offsetX = 0f
                    onExpandChange(null)
                }
            }, onDragCancel = {
                offsetX = 0f
                onExpandChange(null)
            }, onHorizontalDrag = { change, dragAmount ->
                val newOffset = offsetX + dragAmount
                offsetX = newOffset.coerceIn(maxOffset, 0f)
                change.consume()
            })
        }) {
        Box(
            modifier = Modifier
                .fillMaxHeight()
                .align(Alignment.CenterEnd)
                .onGloballyPositioned {
                    revealWidth = it.size.width
                }) {
            revealContent()
        }

        Box(
            modifier = Modifier
                .offset { IntOffset(animatedOffset.roundToInt(), 0) }
                .background(Color.White)
                .clickable {
                    if (offsetX != 0f) {
                        offsetX = 0f
                        onExpandChange(null)
                    }
                }) {
            content()
        }
    }
}

@Composable
fun TaskEntry(title: String, content: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 5.dp),  // android:layout_marginVertical="5dp"
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = title,
            style = MaterialTheme.typography.bodySmall,
            modifier = Modifier.width(100.dp)
        )
        Text(
            text = content,
            style = MaterialTheme.typography.bodySmall,
            modifier = Modifier
                .weight(1f)        // 占满剩余宽度
                .wrapContentWidth(Alignment.End) // 右对齐内容
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TitleBar() {
    CenterAlignedTopAppBar(
        title = {
            Text(
                "任务列表", maxLines = 1, overflow = TextOverflow.Ellipsis
            )
        }, colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer,
            titleContentColor = MaterialTheme.colorScheme.primary,
        ), actions = {
            IconButton(onClick = {}) {
                Icon(
                    imageVector = Icons.Filled.Add, contentDescription = "添加任务"
                )
            }
        })
}

@ExperimentalMaterial3Api
@Composable
fun SingleSelectChipGroup(
    tags: List<TaskGroupTagBean>,
    select: TaskGroupTagBean?,
    callback: (TaskGroupTagBean) -> Unit = {}
) {
    Row(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
        Log.d("====", "tas=$tags select=$select")
        tags.forEach { option ->
            FilterChip(
                selected = select?.id == option.id,
                onClick = {
                    callback(option)
                }, label = { Text(option.name) }, modifier = Modifier
            )
        }
    }
}

@Composable
fun ExpandableFab(
    actions: List<FabAction>,
    icon: ImageVector,
    expanded: Boolean,
    onFabClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Box(modifier) {
        // 子按钮（从下往上显示）
        Column(
            verticalArrangement = Arrangement.spacedBy(12.dp),
            horizontalAlignment = Alignment.End,
            modifier = Modifier
                .padding(bottom = 72.dp, end = 16.dp)
                .align(Alignment.BottomEnd)
        ) {
            if (expanded) {
                actions.forEach { action ->
                    FloatingActionButton(
                        onClick = action.onClick,
                        containerColor = MaterialTheme.colorScheme.secondaryContainer,
                        contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
                        modifier = Modifier.size(48.dp)
                    ) {
                        TextButton(
                            onClick = action.onClick
                        ) {
                            Text(action.label, style = MaterialTheme.typography.bodyMedium)
                        }
                    }
                }
            }
        }

        // 主按钮
        FloatingActionButton(
            onClick = onFabClick,
            modifier = Modifier
                .align(Alignment.BottomEnd)
                .padding(end = 16.dp, bottom = 16.dp)
        ) {
            Icon(icon, contentDescription = "展开")
        }
    }
}

@Preview()
@Composable
fun itemPriview() {
    TaskItem(Task().also {
        it.name = "测试名称"
        it.command = "脚本名称"
    })
}